import Vue from 'vue';
//1.引入vue-router
import VueRouter from 'vue-router';

//引入子组件，通过哈希值切换不同组件
import Home from '../components/Home';
import Brand from '../components/Brand';
import Cart from '../components/Cart';
import Classify from '../components/Classify';
import Details from '../components/Details';
import List from '../components/List';
import Login from '../components/Login';
import My from '../components/My';
import Reg from '../components/Reg';
import Notfound from '../components/Notfound';


//2.使用vue-router（script标签引入方式自动完成）
Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};
//3.实例化router并配置参数
let router = new VueRouter({
    routes: [
        //首页的路由
        {
            name: 'home',
            path: '/home',  //当浏览器地址为/home时，显示Home组件的内容
            component: Home
        },
        {

            path: '/',  //当浏览器地址为/home时，显示Home组件的内容
            redirect: '/home' //重定向
        },
        // 购物车
        {
            name: 'cart',
            path: '/cart',
            component: Cart,
            meta: { //设置该元信息就是为了鉴权
                requiresAuth: true
            }
        },
        {
            name: 'brand',
            path: '/brand',
            component: Brand
        },
        {
            name: 'classify',
            path: '/classify',
            component: Classify
        },
        {
            name: 'details',
            path: '/details',
            component: Details
        },
        {
            name: 'reg',
            path: '/reg',
            component: Reg
        }, {
            name: 'login',
            path: '/login',//获取动态路由
            component: Login
        },
        {
            name: '404',
            path: '/404',
            component: Notfound
        },
        {
            name: '404',
            path: '*',
            redirect: '/404' //重定向
        }, {
            name: 'list',
            path: '/list',
            component: List
        }, {
            name: 'my',
            path: '/my',
            component: My
        }
    ]
});

router.beforeEach(function (to, from, next) {
    if(to.meta.requiresAuth) {
        let token = localStorage.getItem('authorization');

        if(token) {
            next();
        } else {
            router.push({
                name:'login',params:{
                    targeturl:to.path
                }
            })
        }
    } else {
        next();
    }
})

export default router;